package com.beiding.render;

import java.util.Collections;
import java.util.Map;

public class InnerAbleTemplateFinder implements TemplateFinder {

    private TemplateFinder parent;
    private Map<String, TemplateImpl> templateMap = Collections.emptyMap();


    public InnerAbleTemplateFinder(TemplateFinder parent) {
        this.parent = parent;
    }

    public InnerAbleTemplateFinder(TemplateFinder parent, Map<String, TemplateImpl> templateMap) {
        this.parent = parent;
        this.templateMap = templateMap;
    }

    public void setTemplateMap(Map<String, TemplateImpl> templateMap) {
        this.templateMap = templateMap;
    }

    @Override
    public Template findTemplate(String relative, String expression) {
        expression = expression.trim();

        if (expression.startsWith("$")) {

            int index = expression.indexOf("/$");

            if (index != -1) {

                TemplateImpl inner = (TemplateImpl) findTemplate(relative, expression.substring(0, index));
                if (inner == null) {
                    return null;
                }
                //后续的操作一定发生在内部模板中
                return inner.getRenderTime().getTemplateFinder().findTemplate(null, expression.substring(index + 1));
            } else {

                TemplateImpl template = templateMap.get(expression);
                if (template != null) {
                    return template;
                } else {

                    //不再委托和传递
                    if (!(parent instanceof InnerAbleTemplateFinder)) {
                        return null;
                    }

                    return parent.findTemplate(null, expression);
                }

            }

        }

        int index = expression.indexOf("/$");
        if (index != -1) {

            //外部位置
            String outPath = expression.substring(0, index);
            TemplateImpl outTemplate = (TemplateImpl) parent.findTemplate(relative, outPath);

            if (outTemplate == null) {
                return null;
            }

            return outTemplate.getRenderTime().getTemplateFinder().findTemplate(outTemplate.getCoordinate(), expression.substring(index + 1));

        } else {
            return parent.findTemplate(relative, expression);
        }
    }
}

